package org.fu.crowd.controller;

import org.fu.crowd.api.MySQLRemoteService;
import org.fu.crowd.config.OSSProperties;
import org.fu.crowd.constant.CrowdConstant;
import org.fu.crowd.utils.Common;
import org.fu.crowd.utils.CrowdUtils;
import org.fu.crowd.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectController {

    //上传图片到OOS所需要的一些信息
    @Resource
    private OSSProperties ossProperties;
    //
    @Resource
    private MySQLRemoteService mySQLRemoteService;


//***********************************    start-step-1.html********************************************

    /**
     *          收集项目信息  start-step-1.html
     *
     * @param projectVO             除了图片之外的其他数据 。图片信息要上传到oos然后再放进来
     * @param headerPicture         接收上传的头图
     * @param detailPictureList 接收上传的详情的图片
     * @param session
     * @return  包含项目信息的ProjectVO
     */
    @RequestMapping("/project/start-step-2")
    public String startStep2(ProjectVO projectVO, MultipartFile headerPicture,
                             MultipartFile[] detailPictureList,
                             HttpSession session, Model model) throws Exception {


        //上传头图
        boolean headerPictureEmpty = headerPicture.isEmpty();
        //若头图不为空
        if (!headerPictureEmpty) {
            //上传到oss
            Common<String> uploadFileToOss = CrowdUtils.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccesskeyId(),
                    ossProperties.getAccessKeySecret(),
                    headerPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(), headerPicture.getOriginalFilename());
            //判断是否上传成功
            String ossResult = uploadFileToOss.getResult();
            if (Common.SUCCESS.equals(ossResult)) {
                //获取访问路径
                String headerPicturePath = uploadFileToOss.getData();
                projectVO.setHeaderPicturePath(headerPicturePath);
            } else {
                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
                return "start-step-1";
            }
        }else {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_ISNULL);
            return "start-step-1";
        }

        //遍历detailPicturePathList，里面包含详情图片
        //先创建一个用来存放详情图片的集合
        List<String> detailPicturePathListVO = new ArrayList<>();
        if (detailPictureList != null && detailPictureList.length > 0) {
            for (MultipartFile multipartFile : detailPictureList) {
                //上传到oss
                Common<String> picturePathListCommon = CrowdUtils.uploadFileToOss(
                        ossProperties.getEndPoint(),
                        ossProperties.getAccesskeyId(),
                        ossProperties.getAccessKeySecret(),
                        multipartFile.getInputStream(),
                        ossProperties.getBucketName(),
                        ossProperties.getBucketDomain(),
                        multipartFile.getOriginalFilename());
                String picturePathListCommonResult = picturePathListCommon.getResult();
                //上传成功
                if (Common.SUCCESS.equals(picturePathListCommonResult)) {
                    String picturePathListCommonData = picturePathListCommon.getData();
                    detailPicturePathListVO.add(picturePathListCommonData);//放入集合中
                }
            }
        }
        //将存放详情图片的集合存入到projectVO中
        projectVO.setDetailPicturePathList(detailPicturePathListVO);

        //将projectVO存入session中
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT,projectVO);

        return "redirect:/project/startStep2";
    }







//***********************************    start-step-2.html********************************************



    /**
     * 回报设置中start-step-2.html     保存图片到OOS
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/project/create/upload/return/picture")
    public Common<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile returnPicture) throws Exception {
        //上传到oss
        Common<String> uploadFileToOss = CrowdUtils.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccesskeyId(),
                ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(), returnPicture.getOriginalFilename());
        //无论有没有上传成功，都把信息发送会前端
        return uploadFileToOss;
    }


    /**
     *      添加回报信息，并放入projectVO中
     * @param returnVO
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/project/create/save/return")
    public Common<String> saveReturn(ReturnVO returnVO,HttpSession session){
        //读取上个页面收集的项目信息
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);
        System.out.println(projectVO);
        if (projectVO == null){
            return Common.failed("project对象丢失");
        }
        //从projectVO中获取存储回报信息的集合,并判断是否有效，无效则创建一个
        List<ReturnVO> returnList = projectVO.getReturnVOList();
        if (returnList == null || returnList.size()==0){
            returnList = new ArrayList<>();
        }
        //将收集的returnVO放入集合中
        returnList.add(returnVO);
        projectVO.setReturnVOList(returnList);
        //重新存入session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT,projectVO);
//        System.out.println(session.getAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT));
        return Common.successWithoutData();
    }

//
//    @ResponseBody
//    @RequestMapping("/project/create/save/return")
//    public Common<String> saveReturn(HttpSession session){
//        System.out.println(session.getAttribute("tempProjectVO"));
//        session.setAttribute("tempProjectVO","aaaa");
//        System.out.println(session.getAttribute("tempProjectVO"));
//        return Common.successWithoutData();
//    }





//***********************************    start-step-3.html********************************************


    @RequestMapping("/project/create/confirm")
    public String saveConfirm(MemberConfirmInfoVO memberConfirmInfoVO , HttpSession session,Model model){
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);
        //先将session域的projectVO取出
        if (projectVO==null){
            throw new RuntimeException("错误");
        }
        //将确认信息放入projectVO中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);
        //获取memberID
        MemberLoginV0 memberLoginV0 = (MemberLoginV0) session.getAttribute(CrowdConstant.LOGIN_MEMBER);
        Integer id = memberLoginV0.getId();
        //调用远程方法保存projectVO
        Common<String> saveProjectV0Common = mySQLRemoteService.saveProjectVORemote(projectVO,id);
        //判断远程的操作是否成功
        String result = saveProjectV0Common.getResult();
        if (Common.FAILED.equals(result)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,saveProjectV0Common.getMessage());
            return "redirect:/project/startStep3";
        }
        //如果保存成功，将projectVO从session域中移除
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);
        return "redirect:/project/startStep4";
    }



    /**
     *  展示给前台的项目详情
     */
    @RequestMapping("/project/portal/showProjectDetail")
    public String getPortalShowProjectDetail(@RequestParam("projectId")Integer projectId,Model model){
        Common<DetailProjectVO> portalShowProjectDetail = mySQLRemoteService.getPortalShowProjectDetail(projectId);
        if (Common.SUCCESS.equals(portalShowProjectDetail.getResult())){
            DetailProjectVO dataProjectVO = portalShowProjectDetail.getData();
            model.addAttribute("dataProjectVO",dataProjectVO);
        }
        return "project-detail";
    }


}
